<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2018/5/28
 * Time: 下午3:50
 */

namespace App\Modules\Order\Services;


use App\Libs\Pay\WechatPay;
use App\Modules\Order\Models\Order;

class OrderService
{
    const ORDER_STATUS_UNPAID=0; #未支付
    const ORDER_STATUS_PAID=1;   #已支付
    const ORDER_STATUS_FAILED=2; #支付失败
    const ORDER_STATUS_REFUND=3; #退款
    /*const ORDER_STATUS_STR_TO_NUM_HASH = [
        'unpaid' => 0,
        'paid' =>1,
        'failed' => 2,
        'refund' => 3,
        'prepare'=>4,
        'packaged'=>5,
        'delivered'=>6,
        'received' =>7
    ];
    const ORDER_STATUS_NUM_TO_STR_HASH = [
        0 => 'unpaid',
        1 => 'paid',
        2 => 'failed',
        3 => 'refund',
        4 => 'prepare',
        5 => 'packaged',
        6 => 'delivered',
        7 => 'received'
    ];*/

    /**
     * 保存一个未支付的订单
     * @param array $data
     * @return mixed
     */
    public static function saveUnPAIDOrder($data = []) {
        $data['status'] = self::ORDER_STATUS_UNPAID;

        return Order::create($data);
    }

    /**
     * 更具ID查询
     * @param $id
     * @return mixed
     */
    public static function findById($id) {
        return Order::find($id);
    }

    /**
     * 更具订单号查询
     * @param $trade_no
     * @return mixed
     */
    public static function findByTradeNo($trade_no) {
        return Order::where('trade_no', $trade_no)->first();
    }

    /**
     * @param $pay_data
     * @return array|mixed
     */
    public static function create_unpay($pay_data) {
        $wechatPay = self::getWechatPayInstance();
        $payResultInfo = $wechatPay->send($pay_data);
        if(!$payResultInfo || count($payResultInfo) == 0){
            $payResultInfo = $wechatPay->send($pay_data);
        }
        return $payResultInfo;
    }

    /**
     * @return \App\Libs\Pay\Merchants\OfficialPay
     */
    public static function getWechatPayInstance() {
        $payConfig = array(
            'appid'=>env('WECHAT_APPID'),
            'secret'=>env('WECHAT_APP_SECRET'),
            'token'=>env('WECHAT_TOKEN'),
            'merchant_id'=>env('WECHAT_PAY_MERCHANT_ID'),
            'key'=>env('WECHAT_PAY_KEY'),
            'cert_path'=>env('WECHAT_PAY_CERT_PATH'),
            'key_path'=>env('WECHAT_PAY_KEY_PATH')
        );
        $wechatPay = WechatPay::instance($payConfig);
        return $wechatPay;
    }
}